﻿using System;
using System.Threading;
using Gsiot.PachubeClient;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;

public class HelloPachube
{
    public static void Main()
    {
        const string apiKey = "<insert your API key here>";
        const string feedId = "<insert your feed ID here>";
        const int samplingPeriod = 10000;   // 10 seconds

        const double maxVoltage = 3.3;
        const int maxAdcValue = 1023;

        var voltagePort = new AnalogInput(Pins.GPIO_PIN_A1);
        var lowPort = new OutputPort(Pins.GPIO_PIN_A0, false);
        var highPort = new OutputPort(Pins.GPIO_PIN_A2, true);

        while (true)
        {
            WaitUntilNextPeriod(samplingPeriod);
            int rawValue = voltagePort.Read();
            double value = (rawValue * maxVoltage) / maxAdcValue;
            string sample = "voltage," + value.ToString("f");
            Debug.Print("new message: " + sample);
            PachubeClient.Send(apiKey, feedId, sample);
        }
    }

    static void WaitUntilNextPeriod(int period)
    {
        long now = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
        var offset = (int)(now % period);
        int delay = period - offset;
        Debug.Print("sleep for " + delay + " ms\r\n");
        Thread.Sleep(delay);
    }
}
